﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Win32;


namespace OnlineExamClient
{
    public partial class FrmMain : Form
    {
        //勾子管理类
        private KeyboardHookLib _keyboardHook = null;
        private bool isShowExitDlg = false;
        private delegate void Show_Dlg();
        #region 关机用到的API代码

        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        internal struct TokPriv1Luid
        {
            public int Count;
            public long Luid;
            public int Attr;

        }
        private const int SW_HIDE = 0;
        private const int SW_RESTORE = 9;

        [DllImport("user32.dll")]
        public static extern int ShowWindow(int hwnd, int nCmdShow);
        [DllImport("user32.dll")]
        public static extern int FindWindow(string lpClassName, string lpWindowName);
       
        [DllImport("kernel32.dll", ExactSpelling = true)]
        internal static extern IntPtr GetCurrentProcess();

        [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
        internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);

        [DllImport("advapi32.dll", SetLastError = true)]
        internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);

        [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
        internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen); 
        
        [DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
        internal static extern bool ExitWindowsEx(int flg, int rea);        
        internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
        internal const int TOKEN_QUERY = 0x00000008;
        internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
        internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege"; 
        internal const int EWX_LOGOFF = 0x00000000;//注销
        internal const int EWX_SHUTDOWN = 0x00000001;//关机
        internal const int EWX_REBOOT = 0x00000002;//重新启动
        internal const int EWX_FORCE = 0x00000004;//强制注销
        internal const int EWX_POWEROFF = 0x00000008;//强制关机
        internal const int EWX_FORCEIFHUNG = 0x00000010;
        private void DoExitWin(int flg)
        {

            bool ok;
            TokPriv1Luid tp;
            IntPtr hproc = GetCurrentProcess();
            IntPtr htok = IntPtr.Zero;
            ok = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
            tp.Count = 1;
            tp.Luid = 0;
            tp.Attr = SE_PRIVILEGE_ENABLED;
            ok = LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref tp.Luid);
            ok = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
            ok = ExitWindowsEx(flg, 0);
        }
        #endregion

        public FrmMain()
        {
            InitializeComponent();
            webBrowser.ScriptErrorsSuppressed = true;          
            this.Width = Screen.PrimaryScreen.Bounds.Width;
            this.Height = Screen.PrimaryScreen.Bounds.Height;   
            //RegistryKey key = Registry.CurrentUser;
            //RegistryKey key1 = key.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Policies\System");           
            //key1.SetValue("DisableTaskMgr", 1, RegistryValueKind.DWord);
            //ShowWindow(FindWindow("Shell_TrayWnd", null), SW_HIDE); //隐藏
            //安装勾子
            _keyboardHook = new KeyboardHookLib();
            _keyboardHook.InstallHook(this.OnKeyPress);       
     
        }

        /// <summary>
        /// 客户端键盘捕捉事件.
        /// </summary>
        /// <param name="hookStruct">由Hook程序发送的按键信息</param>
        /// <param name="handle">是否拦截</param>
        public void OnKeyPress(KeyboardHookLib.HookStruct hookStruct, out bool handle)
        {
            handle = false; //预设不拦截任何键

            if (hookStruct.vkCode == 91) // 截获左win(开始菜单键)
            {
                handle = true;
            }

            if (hookStruct.vkCode == 92 || hookStruct.vkCode == 93)// 截获右win
            {
                handle = true;
            }

            //截获Ctrl+Esc
            if (hookStruct.vkCode == (int)Keys.Escape && (int)Control.ModifierKeys == (int)Keys.Control)
            {
                handle = true;
            }

            //截获alt+f4
            if (hookStruct.vkCode == (int)Keys.F4 && (int)Control.ModifierKeys == (int)Keys.Alt)
            {
                handle = true;
                if (!isShowExitDlg)
                {
                    isShowExitDlg = true;
                    Thread th = new Thread(threadShow);
                    th.Start();
                }
               
            }

            //截获alt+tab
            if (hookStruct.vkCode == (int)Keys.Tab && (int)Control.ModifierKeys == (int)Keys.Alt)
            {
                handle = true;
            }

            //截获F1
            if (hookStruct.vkCode == (int)Keys.F1)
            {
                handle = true;
            }

            //截获Ctrl+Alt+Delete
            if ((int)Control.ModifierKeys == (int)Keys.Control + (int)Keys.Alt + (int)Keys.Delete)
            {
                handle = true;
            }

            ////如果键A~Z
            //if (hookStruct.vkCode >= (int)Keys.A && hookStruct.vkCode <= (int)Keys.Z)
            //{
            //    //挡掉B键
            //    if (hookStruct.vkCode == (int)Keys.B)
            //        hookStruct.vkCode = (int)Keys.None; //设键为0

            //    handle = true;
            //}

            //Keys key = (Keys)hookStruct.vkCode;
            //label1.Text = "你按下:" + (key == Keys.None ? "" : key.ToString());

        }
        private void threadShow()
        {
            try
            {
                Show_Dlg dlg = new Show_Dlg(show_exit);
                Invoke(dlg);
            }
            catch { }
        }
        private void show_exit()
        {            
            FrmExit frm = new FrmExit();
            frm.ShowDialog(this);
            if (frm.ExitPass == "13975873422")
            {
                Application.Exit();
            }
            isShowExitDlg = false;
        }


        private void FrmMain_Load(object sender, EventArgs e)
        {
            try
            {
                String[] keys = ConfigurationManager.AppSettings.AllKeys;
                

                cbSite.DisplayMember = "name";
                cbSite.ValueMember = "url";
                if (keys.Length < 1)
                {
                    cbSite.Items.Add(new SiteData { name = "主站点", url = "http://172.28.7.5/onlineExamSys/login.html" });
                    cbSite.Items.Add(new SiteData { name = "备用站点1", url = "http://172.28.7.6:8080/onlineExamSys/login.html" });
                    cbSite.Items.Add(new SiteData { name = "备用站点2", url = "http://172.28.7.7:8080/onlineExamSys/login.html" });
                    cbSite.Items.Add(new SiteData { name = "备用站点3", url = "http://172.28.7.5:8080/onlineExamSys/login.html" });
                    cbSite.Items.Add(new SiteData { name = "备用站点4", url = "http://172.28.7.6:9080/onlineExamSys/login.html" });
                    cbSite.Items.Add(new SiteData { name = "备用站点5", url = "http://172.28.7.7:9080/onlineExamSys/login.html" });
                    cbSite.Items.Add(new SiteData { name = "备用站点6", url = "http://172.28.7.5:9080/onlineExamSys/login.html" });
                }
                else
                {
                    foreach (string key in keys)
                    {
                        string v = ConfigurationManager.AppSettings[key];
                        v = v.ToLower();
                        if (!string.IsNullOrEmpty(v) && v.StartsWith("http://"))
                        {
                            if (v.EndsWith("/"))
                            {
                                v = v + "onlineExamSys/login.html";
                            }
                            else
                            {
                                v = v + "/onlineExamSys/login.html";
                            }
                            cbSite.Items.Add(new SiteData { name = key, url = v });
                        }
                    }
                }

                string title = ConfigurationManager.AppSettings["title"];
                if (!string.IsNullOrEmpty(title))
                {
                    title = title + "V2.20191201-IE" + webBrowser.Version.ToString();
                    this.Text = title;
                    label1.Text = title;
                }else
                {
                    title = "长沙民政职业技术学院在线考试系统客户端";
                    title = title + "V2.20191201-IE" + webBrowser.Version.ToString();
                    this.Text = title;
                    label1.Text = title;
                }
            }
            catch { }
            if (cbSite.Items.Count > 0)
            {
                cbSite.SelectedIndex = 0;
                //SiteData site = cbSite.Items[0] as SiteData;
                //webBrowser.Url = new Uri(site.url);
            }
                        
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            //取消勾子
            if (_keyboardHook != null) _keyboardHook.UninstallHook();
            ShowWindow(FindWindow("Shell_TrayWnd", null), SW_RESTORE); //显示            
        }
       
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            webBrowser.Refresh();
        }
        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (cbSite.SelectedIndex < 0) return;
            SiteData site = cbSite.Items[cbSite.SelectedIndex] as SiteData;
            webBrowser.Url = new Uri(site.url);
        }    

        private void cbSite_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbSite.SelectedIndex < 0) return;
            SiteData site = cbSite.Items[cbSite.SelectedIndex] as SiteData;
            webBrowser.Url = new Uri(site.url);
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            DialogResult rs = MessageBox.Show("你提交试卷了吗？退出将结束本次考试！", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
           if (rs == System.Windows.Forms.DialogResult.OK)
           {
               Application.Exit();
               //try
               //{
               //    this.DoExitWin(EWX_SHUTDOWN);

               //}
               //catch
               //{
               //    try
               //    {
               //        this.DoExitWin(EWX_POWEROFF);
               //    }
               //    catch { }
               //}
           }
        }


        private void webBrowser_NewWindow(object sender, CancelEventArgs e)
        {
            string url = ((WebBrowser)sender).StatusText;
            webBrowser.Navigate(url);
            e.Cancel = true;
        }

        private void FrmMain_Deactivate(object sender, EventArgs e)
        {
            this.Activate();
        }           
    }
}
